package com.lfz.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis配置类
 * @author Daniel
 */
@Configuration
public class RedisContextConfiguration {

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public StringRedisTemplate stringRedisTemplate(){
        StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
        // 显示开启事务支持，默认不开启
        // template.setEnableTransactionSupport(true);
        return template;
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
        connectionFactory.setHostName(redisProperties.getHost());
        connectionFactory.setPort(redisProperties.getPort());
        connectionFactory.setDatabase(redisProperties.getDatabase());
        connectionFactory.setTimeout(redisProperties.getTimeout());
        connectionFactory.setPoolConfig(poolConfig());
        return connectionFactory;
    }

    @Bean
    public JedisPoolConfig poolConfig() {
        RedisProperties.Pool pool = redisProperties.getPool();
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(pool.getMaxIdle());
        poolConfig.setMinIdle(pool.getMinIdle());
        poolConfig.setMaxTotal(pool.getMaxActive());
        poolConfig.setMaxWaitMillis(pool.getMaxWait());
        return poolConfig;
    }

}
